package com.example.nacosdemo.controller;

import com.example.nacosdemo.service.ServiceConsumer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 服务消费者控制器
 * 用于测试服务间调用功能
 */
@RestController
public class ServiceConsumerController {

    @Autowired
    private ServiceConsumer serviceConsumer;

    /**
     * 调用指定服务的配置接口
     * @param serviceName 服务名称
     * @return 调用结果
     */
    @GetMapping("/consumer/call/{serviceName}")
    public Map<String, Object> callService(@PathVariable String serviceName) {
        Map<String, Object> result = new HashMap<>();
        result.put("targetService", serviceName);
        result.put("timestamp", System.currentTimeMillis());
        result.put("result", serviceConsumer.callServiceConfig(serviceName));
        return result;
    }

    /**
     * 获取注册到Nacos的服务列表
     * @return 服务列表
     */
    @GetMapping("/consumer/services")
    public List<String> getServices() {
        return serviceConsumer.getRegisteredServices();
    }

    /**
     * 获取指定服务的所有实例
     * @param serviceName 服务名称
     * @return 服务实例列表
     */
    @GetMapping("/consumer/instances/{serviceName}")
    public List<ServiceInstance> getInstances(@PathVariable String serviceName) {
        return serviceConsumer.getServiceInstances(serviceName);
    }

    /**
     * 调用自身服务的配置接口（演示用）
     * @return 配置信息
     */
    @GetMapping("/consumer/call-self")
    public Map<String, Object> callSelf() {
        Map<String, Object> result = new HashMap<>();
        result.put("targetService", "self");
        result.put("timestamp", System.currentTimeMillis());
        result.put("result", serviceConsumer.callSelfConfig());
        return result;
    }
}